package com.liyujie.serialport.utils.activation;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;

public class Authorize {
    private  static final String  Key="ilinai.com";
    public  static  boolean Auth(String ActiveCode)
    {
        //把HexString转成byte[]
        byte[] b_code =ConvertUtils.hexString2Bytes(ActiveCode);
        byte[] b_plaintext = RC4.encry_RC4_byte(b_code,Key);

        String DeviceNum = ConvertUtils.bytes2HexString(new byte[]{b_plaintext[0],b_plaintext[1]}).toUpperCase();

        int AuthDay = Byte.toUnsignedInt(b_plaintext[3]) * 256 + Byte.toUnsignedInt(b_plaintext[2]);

        int AcitveDay = Byte.toUnsignedInt( b_plaintext[5]) * 256 + Byte.toUnsignedInt(b_plaintext[4]);

        int CRC =Byte.toUnsignedInt( b_plaintext[7]) * 256 + Byte.toUnsignedInt(b_plaintext[6]);

        int c_crc = CRC16.CRC16_MODBUS(b_plaintext,0,6);

        int currentDay = GetDay();

        if(CRC == c_crc && ( DeviceNum.equals("0000") || DeviceNum.equals(GetDeviceNum())) && AcitveDay >= currentDay && AuthDay> currentDay) {
            //执行激活操作，保存设备的激活有效截至时间
            // ToDo............
            SPUtils.getInstance().put("FactoryManagement",AuthDay);

            return  true;
        }
        return  false;
    }

    public  static  boolean AuthCheck()
    {
        return GetAuthDay()>= GetDay();
    }

    //获取自2022年1月1日以来的天数-
    private static int GetDay()
    {
        // ToDo............
        return (int)Math.abs(TimeUtils.getTimeSpanByNow("2022-1-1 00:00:00", TimeConstants.DAY));
    }

    //获取设备的激活有效截至时间
    private  static int GetAuthDay() {

        int date = (int) Math.abs(TimeUtils.getTimeSpanByNow("2023-1-10 00:00:00", TimeConstants.DAY));
        // ToDo............
        return SPUtils.getInstance().getInt("FactoryManagement",(date  * 24));
    }

    public static  String GetDeviceNumSERIAL() {
        String SERIAL = android.os.Build.SERIAL.toUpperCase();
        if(SERIAL.length() > 8){
            return  SERIAL.substring(0,8);
        }else {
            return  SERIAL;
        }
    }

    private static  String GetDeviceNum() {
      String res = EncryptUtils.encryptMD5ToString(GetDeviceNumSERIAL()).substring(0,4).toUpperCase();
      return  res;
    }
}
